package com.su.Servlet;

import javax.crypto.CipherOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import static java.lang.System.out;

public class CookieDemo extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码问题
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        PrintWriter out = resp.getWriter();
        //获取Cookie的值
        Cookie[] cookies = req.getCookies();
        //遍历Cookie
        for(int i= 0;i < cookies.length;i++){
            if(cookies[i]!=null){
                Cookie cookie1 = cookies[i];
                if(cookie1.getName().equals("LasterloginTime")){
                    //获取Cookie的值
                    long lasterlongTime = Long.parseLong(cookie1.getValue());
                    Date date = new Date(lasterlongTime);
                    out.write(date.toLocaleString());
                }
            } else{
                out.write("第一次访问Cookie");
            }
            /*
            Cookie是以字符串进行存储
            若想存汉字可以往编码，解码中想
            URLEncode.encode(str, "UTF-8");编码
           // URLDecode.decode(str, "UTF-8");解码
             */


        }
            //设置Cookie
            Cookie cookie = new Cookie("LasterloginTime",System.currentTimeMillis()+"");
            //设置Cookie的存活时间
            cookie.setMaxAge(60*60*24);
            resp.addCookie(cookie);
    }
}

